<template>
  <customContainer ref="customContainerRef" :config="mainConfig" />
  <div>
    <feeName ref="feeRef"></feeName>
    <el-dialog
      v-model="open"
      width="1200px"
      :title="'客户单号: ' + waybillNo"
      :fullscreen="false"
      :close-on-click-modal="false"
    >
      <upsPreparation></upsPreparation>
      <div>
        <el-row>
          <el-col :span="24">
            <el-row class="sums">
              <el-col :span="4">合计</el-col>
              <!-- <el-col :span="4">实重：{{ sums.totalWeight }}</el-col>
              <el-col :span="4">体积重：{{ sums.vWeight }}</el-col>
              <el-col :span="4">计费重：{{ sums.jWeight }}</el-col>
              <el-col :span="4">实重：{{ sums.bweight }}</el-col>
              <el-col :span="4">件数：{{ sums.shipmentTotal }}</el-col> -->
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-button type="primary" @click="handlePreparationEnd">
              打单完成
            </el-button>

            <el-button @click="upsClose">关闭</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog v-model="open2" width="400px" title="撤单">
      <div>
        <h3>此操作将永久删除该订单，是否继续？</h3>
        <el-form ref="remarkRef" :model="cdRemark" :rules="rules1">
          <el-form-item prop="remarks" label="备注">
            <el-input
              v-model="cdRemark.remarks"
              style="width: 200px;"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>  
        <el-button type="info" @click="close2">取消</el-button>
        <el-button v-loading="btnLoading" type="primary" @click="cdSumit">确定</el-button>
      </div>
    </el-dialog>
    <edit
      :id="rowId"
      ref="editRef"
      :order-no="rowOrderNo"
      @changeList="handleQuery"
    ></edit>
  </div>
</template>
<script lang="ts" setup>
// import { Delete, Refresh, Plus, Download, Edit, Document, Calendar, UploadFilled } from '@element-plus/icons-vue'
import { ref, defineAsyncComponent, watch, onMounted, computed, getCurrentInstance } from 'vue'
import { ElButton, ElMessage, ElDivider } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { listTable, getOrderDetail, delOrderTerminalInfo } from '@/api/expressManager/outSea'
import { replaceParams, addDateRange } from '@/utils/index'

const feeName = defineAsyncComponent(() => import('./components/feeName.vue'))
const upsPreparation = defineAsyncComponent(() => import('./components/upsPreparation.vue'))
const edit = defineAsyncComponent(() => import('./components/edit.vue'))
const SelfDropdown = defineAsyncComponent(() => import('./components/SelfDropdown.vue'))
const dicts = useDicts()
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.客户)
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.货物类型)
dicts.setDicts(DictDirection.报价类型)
dicts.setDicts(DictDirection.收货站点)
dicts.setDicts(DictDirection.业务员)
dicts.setDicts(DictDirection.包裹状态)
const { proxy } = getCurrentInstance() as any
const single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  remarkRef = ref(null),
  customContainerRef = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $download, $validateForm },
      },
    },
  } = getCurrentInstance()
const feeRef = ref(undefined)
const editRef = ref(null)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  waybillNo: '',
  mainTransferOrderNo: '',
  consigneeCountry: '',
  consigneePostcode: '',
  beginTime: '',
  endTime: '',
  dateRange: '',
  zDdateRange: '',
  makerBeginTime: '',
  makerEndTime: '',
})
const rules1 = {
  remarks: [{
    required: true,
    message: '必填',
    trigger: ['change', 'blur'],
  }],
}
const cdRemark = ref({
  remarks: '',
})
// const handleInitData = () => {
//   proxy.queryParams.zDdateRange ? (proxy.queryParams.makerBeginTime = proxy.queryParams.zDdateRange[0]) : (proxy.queryParams.makerBeginTime = '')
//   proxy.queryParams.zDdateRange ? (proxy.queryParams.makerEndTime = proxy.queryParams.zDdateRange[1]) : (proxy.queryParams.makerEndTime = '')
//   const queryParam = JSON.parse(JSON.stringify(proxy.queryParams))
//   console.log(queryParam.orderNo)
  
//   queryParam.orderNo = replaceParams(proxy.queryParams.orderNo)
//   queryParam.mainTransferOrderNo = replaceParams(queryParams.value.mainTransferOrderNo)
//   queryParam.waybillNo = replaceParams(queryParams.value.waybillNo)
//   const data = addDateRange(queryParam, proxy.queryParams.dateRange)
//   return data
// }

// watch(() => queryParams.value,
//   (news, olds) => {
//     const data = handleInitData()
//     queryParams.value = data
//     // queryParams.value.beginTime = news[0]
//     // queryParams.value.endTime = news[1]
//     console.log(news, olds)
//   }, {
//     deep: true,
//   })
const open = ref(false)
const open2 = ref(false)
// 导出
const exportHand = (row: { [key: string]: any }) => {
  const id = row?.id
  console.log(id)
  
  let data
  const orderIdList = JSON.parse(JSON.stringify(orderIdLists.value))
  
  if (orderIdList.length != 0) {
    const orderIdList = JSON.parse(JSON.stringify(orderIdLists.value))
    data = orderIdList
  } 
  
  return $download('order/orderTerminalInfo/export', { orderIdList: data }, `海外仓列表_${ new Date().getTime() }.xlsx`)
}
// 应收费
const handleManagementOfSurcharges = (row: { [key: string]: any }) => {
  feeRef.value.feeOpen = true
  feeRef.value.title = '应收费'
  feeRef.value.orderNos = row.orderNo
  feeRef.value.getList()
}
// 打单
const handleUps = () => {
  open.value = true
}
// 撤单
const btnLoading = ref(false)
const idss = ref(null)
const handleDel = (row: { [key: string]: any }) => {
  idss.value = row.id
  open2.value = true
}
const cdSumit = () => {
  const cdid = idss.value
  const remarks = cdRemark.value.remarks
  btnLoading.value = true
  $validateForm(remarkRef.value, () => {
    delOrderTerminalInfo(cdid, { remark: remarks }).then(res => {
      if (res.code == 200) {
        ElMessage.success('撤单成功')
        handleQuery()
        close2()
        btnLoading.value = false
      } else {
        ElMessage.error('撤单失败')
        btnLoading.value = false
      }
    }).catch(() => {
      btnLoading.value = false
    })
  })
}
const close2 = () => {
  open2.value = false
  proxy.$refs[remarkRef].resetFields()
}
// 下载标签
const handleDownLabel = () => {}

const handlePreparationEnd = () => {}
const upsClose = () => {
  open.value = false
}
const rowId = ref([])
const rowOrderNo = ref([])
// 修改
const editInfo = (row: { [key: string]: any }) => {
  editRef.value.idss = row.id
  editRef.value.orderNos = row.orderNo
  editRef.value.title = '修改'
  editRef.value.opens = true
  editRef.value.loading = true
  editRef.value.initData(row.orderNo)
}
// 详情

const openInfo = (row: { [key: string]: any }) => {
  editRef.value.idss = row.id
  editRef.value.orderNos = row.orderNo
  editRef.value.title = '详情'
  editRef.value.opens = true
  // editRef.value.loading = true
  rowId.value = row.id
  rowOrderNo.value = row.orderNo
  editRef.value.initData(row.orderNo)
}

const orderNoLists = ref([])
const orderIdLists = ref([])
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  console.log(rows)
  orderNoLists.value = rows.map((item) => item.orderNo)
  orderIdLists.value = rows.map((item) => item.id)
  single.value = rows.length != 1
  multiple.value = !rows.length
}
const handleQuery = () => {
  queryParams.value.pageNum = 1
  customContainerRef.value.getList()
}
const mainConfig = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '系统订单号',
            prop: 'orderNo',
            option: {
              placeholder: '请输入系统订单号',
              type: 'textarea',
            },
          },
          {
            label: '客户单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入客户单号',
              type: 'textarea',
            },
          },
          {
            label: '主转单号',
            prop: 'mainTransferOrderNo',
            option: {
              placeholder: '请输入主转单号',
              type: 'textarea',
            },
          },
          {
            type: 'select',
            label: '收货类型',
            prop: 'goodsType',
            option: {
              dictInfo: { dict: DictDirection.货物类型 },
            },
          },
          {
            type: 'selectv2',
            label: '目的国家',
            prop: 'consigneeCountry',
            option: {
              dictInfo: { dict: DictDirection.国家 },
            },
          },
          {
            label: '邮编',
            prop: 'consigneePostcode',
            option: {
              controls: false,
              // directives: [['hasPermi', ['number'], 'arg']],
            },
          },

          {
            type: 'date-picker',
            label: '创建日期',
            prop: 'dateRange',
            option: {
              type: 'daterange',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            type: 'date-picker',
            label: '制单时间',
            prop: 'zDdateRange',
            option: {
              type: 'daterange',
              valueFormat: 'YYYY-MM-DD',
            },
          },
        ],
        queryParams: queryParams.value,
      },
      btns: [
        {
          title: '导出',
          type: 'warning',
         
          onClick: exportHand,
			
        },
      ],
      table: {
        // formatter: formatterRules,
		
        columns: [
          { type: 'selection', width: '55' },
          { label: '客户单号', prop: 'waybillNo', width: '150', align: 'center' },
          { label: '主转单号', prop: 'mainTransferOrderNo', width: '150', align: 'center' },
          { label: '客户名称', prop: 'customerName', width: '120', align: 'center' },
          { label: '总实重', prop: 'receivingTotalWeight', align: 'center' },
          { label: '材积重', prop: 'receivingTotalWood', align: 'center' },
          { label: '计费重', prop: 'receivingTotalCharging', align: 'center' },
          { label: '件数', prop: 'receivingTotal', align: 'center' },
          { label: '订单状态',
            prop: 'splittingStatus',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'splittingStatus',
            } },
          { label: '创建日期', prop: 'createDate', align: 'center', width: '180' },
          { label: '邮编', prop: 'consigneePostcode', align: 'center' },
          { label: '国家',
            prop: 'consigneeCountry',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.国家,
              rowKey: 'consigneeCountry',
            } },
          { label: '货物类型',
            prop: 'goodsType',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.货物类型,
              rowKey: 'goodsType',
            } },
          { label: '业务员', prop: 'businessManager', align: 'center' },
          { label: '制单人', prop: 'maker', align: 'center' },
          { label: '制单日期', prop: 'makerDate', align: 'center', width: '120' },
          { label: '备注', prop: 'remarks', align: 'center', width: '80' },
          { label: '系统订单号', prop: 'orderNo', align: 'center', width: '180' },

          {
            label: '操作',
            align: 'center',
            width: '252',
            fixed: 'right',
            render(h, params) {
              const buttons = [ 
                {
                  label: '打单',                
                  clickFun: handleUps,
                },
                {
                  label: '撤单',                
                  clickFun: handleDel,
                },
                {
                  label: '修改',                
                  clickFun: editInfo,
                },
                 
                {
                  label: '下载标签',                
                  clickFun: handleDownLabel,
                },
                
              ]
              return [
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => { openInfo(params.row) },
                  },
                  {
                    default: () => '详情',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    // icon: el.icon,
                    onClick: () => { handleManagementOfSurcharges(params.row) },
                  },
                  {
                    default: () => '应收费',
                  },
                ),
                h(
                  ElDivider,
                  { direction: 'vertical' },
                ),
                h(
                  SelfDropdown,
                  {
                    items: [
                      ...buttons,
                    ],
                    onHandleCommand(command) {
                      command.clickFun && command.clickFun(params.row)
                    },
                  },
                ),
              ]
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: listTable,
      customKey: 'express/mainBusiness/terminalServices/overseaLocation/overSeaOrderInfo',
    }
  },
  set(val) {
    return val
  },
})
</script>